package com.data {
	import com.Interface.IChange;
	import com.Interface.IDrag;
	import com.Interface.IRelayout;
	import config.TConfig;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class DragData {
		public var dragSprite:Sprite;
		private var hitTest:Sprite;
		private var stage:Sprite;
		//是否移动过
		private var isMove:Boolean = false;

		public function DragData(_dragSprite:Sprite, _hitTest:Sprite, _stage:Sprite){
			this.stage = _stage;
			this.dragSprite = _dragSprite;
			this.hitTest = _hitTest;
			for (var i:int = 0; i < (this.dragSprite as IDrag).dragTarget.length; i++){
				(this.dragSprite as IDrag).dragTarget[i].addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			}
		}

		private function onMouseDown(event:MouseEvent):void {
			this.addToStage(event.stageX, event.stageY, event);
			this.dragSprite.startDrag();
			for (var i:int = 0; i < (this.dragSprite as IDrag).dragTarget.length; i++){
				(this.dragSprite as IDrag).dragTarget[i].addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			}
			TConfig.getInstance().stage.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}

		private function addToStage(_x:Number, _y:Number, event:MouseEvent = null):void {
			var point:Point = new Point(_x, _y);
			if (this.stage == null){
				return;
			}
			this.stage.addChild(dragSprite);
			if (hitTest != null){
				//有些专门就是托动不需要碰撞,就没有父对象
				(hitTest as IRelayout).invalist();
			}
			if (!isMove && hitTest != null){
				//重新较正位置
				dragSprite.x = point.x - event.localX;
				dragSprite.y = point.y - event.localY;
				isMove = true;
				(this.dragSprite as IDrag).dragRelayout();
			}
		}

		private function onMouseUp(event:MouseEvent):void {
			TConfig.getInstance().stage.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			this.addToStage(event.stageX, event.stageY);
			this.dragSprite.stopDrag();
			for (var i:int = 0; i < (this.dragSprite as IDrag).dragTarget.length; i++){
				(this.dragSprite as IDrag).dragTarget[i].removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			}
			//如果托动完成,位置还在列表里面,就然后添加回去
			if (hitTest != null && hitTest.hitTestObject(dragSprite)){
				return;
				(dragSprite as IDrag).onClose(null);
				(this.hitTest as IDrag).addDragControl(dragSprite);
				return;
			}
		}

		public function clear():void {
			(this.hitTest as IDrag).addDragControl(dragSprite);
			isMove = false;
			(hitTest as IRelayout).invalist();
			for (var i:int = 0; i < (this.dragSprite as IDrag).dragTarget.length; i++){
				(this.dragSprite as IDrag).dragTarget[i].removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			}
			(this.dragSprite as IDrag).onClose(null);
			this.dragSprite = null;
		}

		public function toBack():void {
			(this.hitTest as IDrag).addDragControl(dragSprite);
			isMove = false;
			(hitTest as IRelayout).invalist();
		}
	}
}